package myProject.gwt.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.TextBoxBase;

public class NumericTextBox extends Composite {

    private int minValue = Integer.MIN_VALUE;
    private int maxValue = Integer.MAX_VALUE;
    private TextBox textBox = new TextBox();
    
    public NumericTextBox() {
        super();
        textBox.setTextAlignment(TextBoxBase.ALIGN_RIGHT);
        initWidget(textBox);
        this.setValue(0);
    }

    public void onBrowserEvent(Event event) {
        super.onBrowserEvent(event);

        if (DOM.eventGetType(event) == Event.ONCHANGE) {
            textBox.setText(String.valueOf(this.getValue()));
        }
    }

    public int getValue() {
        try {
            int value = Integer.parseInt(textBox.getText());
            return Math.max(Math.min(value, this.maxValue), this.minValue);
        } catch (NumberFormatException ex) {
            return Math.max(Math.min(0, this.maxValue), this.minValue);
        }
    }

    public void setValue(int value) {
        textBox.setText(String.valueOf(value));
    }

    public int getMinValue() {
        return minValue;
    }

    public void setMinValue(int minValue) {
        this.minValue = minValue;
    }

    public int getMaxValue() {
        return maxValue;
    }

    public void setMaxValue(int maxValue) {
        this.maxValue = maxValue;
    }

}
